package com.blog.blog.service;

import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ContentModerationService {

	private final List<String> sensitiveWords;

	public ContentModerationService() {
		this.sensitiveWords = loadSensitiveWords();
	}

	private List<String> loadSensitiveWords() {
		try {
			ClassPathResource resource = new ClassPathResource("sensitive-words.txt");
			if (!resource.exists()) return new ArrayList<>();
			try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
				return reader.lines()
						.map(String::trim)
						.filter(s -> !s.isEmpty() && !s.startsWith("#"))
						.sorted((a, b) -> Integer.compare(b.length(), a.length()))
						.collect(Collectors.toList());
			}
		} catch (Exception e) {
			return new ArrayList<>();
		}
	}

	public String sanitize(String content) {
		if (content == null) return null;
		String sanitized = content;
		for (String w : sensitiveWords) {
			if (w.isEmpty()) continue;
			String replacement = repeat('*', Math.min(w.length(), 4));
			sanitized = sanitized.replaceAll("(?i)" + java.util.regex.Pattern.quote(w), replacement);
		}
		return sanitized;
	}

	private String repeat(char c, int count) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < count; i++) sb.append(c);
		return sb.toString();
	}
}



